package utils;

import android.content.ContentProviderClient;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.example.administrator.newxlmedical.MainActivity;

import java.util.ArrayList;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import beans.GoodsDetailsBean;
import beans.LoginBean;
import beans.NewUserInfoBean;
import beans.StorageWarningBean;
import beans.StorageWarningInfoBean;
import beans.UnusedGoodsBean;
import beans.WarningInfoBean;
import constants.Constants;
import constants.HandlerConstant;
import customhandler.MyHandler;
import netframe.GetRetrofit;
import netframe.NetAddress;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import singleton.SingletonClass;

/**
 * Created by Administrator on 2018/8/11.
 */

public class LoginRedCountUtils {

    private boolean isTimeout = false;
    private boolean isWarning = false;
    private boolean isReturn = false;

    private int timeOutCount = 0;
    private int inventoryWarnCount = 0;
    private int returnHintCount = 0;
    private List<StorageWarningInfoBean> warnList = new ArrayList<>();
    private List<WarningInfoBean.DataBean> data = new ArrayList<>();
    private List<StorageWarningInfoBean> lessList;
    private StringBuilder sbUserIds = new StringBuilder();
    private String goodsId = "";
    private String terminalInfoId;
    private String starDate;
    private String endDate;
    private String cabinetInfoIds;
    private NewUserInfoBean.DataBean bean;
    private long startime = 0;
    private long endtime = 0;
    public Map<Integer, String> hashMap = new HashMap<>();
    private StringBuffer sb = new StringBuffer();
    public static MyHandler allHandler = SingletonClass.getSingleton(MyHandler.class);

    public void getRedDotCount(Context context) {

        terminalInfoId = NetAddress.terminalInfoId;

        Object o = ObjectSaveUtil.readObject(context, Constants.CABINETINFO_LOGICNUMBER_HASHMAP, Constants.CABINETINFO_LOGICNUMBER_HASHMAP);

        sb.delete(0, sb.length());
        if (o != null) {
            hashMap = (Map<Integer, String>) o;
            Set set = hashMap.entrySet();
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                Map.Entry mapentry = (Map.Entry) iterator.next();
                sb.append("'" + mapentry.getKey() + "',");
            }
            sb.deleteCharAt(sb.length() - 1);
        }
        loadTimeOut(context);
        loadInventoryWarn(context);
        loadReturnHint(context);

    }

    private void loadInventoryWarn(Context context) {
        postData(context);
    }

    private void loadReturnHint(Context context) {
        loadingTask(context);
    }

    private void loadTimeOut(final Context context) {
        String sql = "select * from GoodsDetails where CabinetInfoId in (" + sb.toString() + ") and DATEADD(dd,-90,LastTime) < getdate() and Status = 3";
        Call<ArrayList<GoodsDetailsBean>> call = GetRetrofit.getInstance().getGoodsDetails(NetAddress.token, NetAddress.machineCode, sql);
        call.enqueue(new Callback<ArrayList<GoodsDetailsBean>>() {
            @Override
            public void onResponse(Call<ArrayList<GoodsDetailsBean>> call, Response<ArrayList<GoodsDetailsBean>> response) {
                ArrayList<GoodsDetailsBean> body = response.body();
                if (body != null) {
                    timeOutCount = body.size();
                } else {
                    timeOutCount = 0;
                }
                NetAddress.TIMEOUT_COUNT = timeOutCount;
                isTimeout = true;
                if (isWarning && isReturn) {
                    Message message = allHandler.obtainMessage();
                    message.what = HandlerConstant.RED_COUNT;
                    message.arg1 = timeOutCount;
                    message.arg2 = inventoryWarnCount;
                    message.obj = returnHintCount;
                    allHandler.sendMessage(message);
                }
            }

            @Override
            public void onFailure(Call<ArrayList<GoodsDetailsBean>> call, Throwable t) {
                isTimeout = true;
                ToastUtil.showToast(context, t.getMessage());
            }
        });
    }

    private void postData(final Context context) {
        GetRetrofit.getInstance().getWarningGoods(NetAddress.token, NetAddress.machineCode, NetAddress.deptCode)
                .enqueue(new Callback<WarningInfoBean>() {
                    @Override
                    public void onResponse(Call<WarningInfoBean> call, Response<WarningInfoBean> response) {
                        warnList.clear();
                        WarningInfoBean body = response.body();
                        if (body != null) {
                            data = body.getData();
                            sbUserIds.delete(0, sbUserIds.length());
                            if (data != null && data.size() != 0) {
                                for (int i = 0; i < data.size(); i++) {
                                    WarningInfoBean.DataBean dataBean = data.get(i);
                                    sbUserIds.append(dataBean.getGID() + ",");
                                    StorageWarningInfoBean bean = new StorageWarningInfoBean();
                                    bean.setGoodsName(dataBean.getGoodName());
                                    bean.setNumber(dataBean.getCount() + "");
                                    bean.setUnit(dataBean.getGoodsUnit());
                                    bean.setSupplier(dataBean.getManufacturer());
                                    bean.setSpecification(dataBean.getSpecification());
                                    bean.setWarnCount("0");
                                    bean.setGID(dataBean.getGID() + "");
                                    warnList.add(bean);
                                }
                                goodsId = sbUserIds.deleteCharAt(sbUserIds.length() - 1).toString();
                                getData(context);

                            } else {
                                isWarning = true;
                                inventoryWarnCount = 0;
                                if (isTimeout && isReturn) {
                                    Message message = allHandler.obtainMessage();
                                    message.what = HandlerConstant.RED_COUNT;
                                    message.arg1 = timeOutCount;
                                    message.arg2 = inventoryWarnCount;
                                    message.obj = returnHintCount;
                                    allHandler.sendMessage(message);
                                }
                                NetAddress.INVENTORY_COUNT = inventoryWarnCount;
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<WarningInfoBean> call, Throwable t) {
                        isWarning = true;
                        ToastUtil.showToast(context, t.getMessage());
                    }
                });
    }

    private void getData(final Context context) {
        GetRetrofit.getInstance().getStorageWarning1(NetAddress.token, NetAddress.machineCode, "select * from StorageWarning where TerminalInfoId =" + NetAddress.terminalInfoId)
                .enqueue(new Callback<List<StorageWarningBean>>() {
                    @Override
                    public void onResponse(Call<List<StorageWarningBean>> call, Response<List<StorageWarningBean>> response) {
                        List<StorageWarningBean> body = response.body();
//                        ToastUtil.showToast(InventoryWarningActivity.this,response.code()+"");
                        if (body != null && body.size() > 0) {
                            for (int j = 0; j < body.size(); j++) {
                                int count = 0;
                                StorageWarningBean warningBean = body.get(j);
                                for (int i = 0; i < warnList.size(); i++) {
                                    StorageWarningInfoBean storageWarningInfoBean = warnList.get(i);
                                    if (Integer.parseInt(storageWarningInfoBean.getGID()) == warningBean.getGoodsInfoId()) {
                                        count++;
                                        if (Integer.parseInt(storageWarningInfoBean.getNumber()) <= warningBean.getWarningCount()) {
                                            inventoryWarnCount++;
                                        }
                                        break;
                                    }
                                }
                                if (count == 0 && warningBean.getWarningCount() != 0) {
                                    inventoryWarnCount++;
                                }
                            }
                        }

                        isWarning = true;
                        if (isTimeout && isReturn) {
                            endtime = System.currentTimeMillis();
                            Message message = allHandler.obtainMessage();
                            message.what = HandlerConstant.RED_COUNT;
                            message.arg1 = timeOutCount;
                            message.arg2 = inventoryWarnCount;
                            message.obj = returnHintCount;
                            allHandler.sendMessage(message);
                        }
                    }

                    @Override
                    public void onFailure(Call<List<StorageWarningBean>> call, Throwable t) {
                        isWarning = true;
                        ToastUtil.showToast(context, t.getMessage());
                    }
                });
    }

    private void loadingTask(final Context context) {
        bean = (NewUserInfoBean.DataBean) ObjectSaveUtil.readObject(context, Constants.USER_INFO_BEAN, Constants.USER_INFO_BEAN);
        int id = bean.getID();
        int roleId = bean.getRoleInfoId();
        if (roleId == Constants.ROLE_HEAD_NURSE || roleId == Constants.ROLE_MANAGE || roleId == Constants.ROLE_FACTORY) {
            id = 0;
        }
        GetRetrofit.getInstance().getUnusedGoods(NetAddress.token, NetAddress.machineCode, NetAddress.deptCode, id + "", "2")
                .enqueue(new Callback<UnusedGoodsBean>() {
                    @Override
                    public void onResponse(Call<UnusedGoodsBean> call, Response<UnusedGoodsBean> response) {
                        sbUserIds.delete(0, sbUserIds.length());
                        UnusedGoodsBean data = response.body();
                        if (data != null) {
                            List<UnusedGoodsBean.DataBean> body = data.getData();
                            if (body != null) {
                                returnHintCount = body.size();
                            } else {
                                returnHintCount = 0;
                            }
                        } else {
                            returnHintCount = 0;
                        }
                        loadingTask1(context);
                    }

                    @Override
                    public void onFailure(Call<UnusedGoodsBean> call, Throwable t) {
                        isReturn = true;
                        ToastUtil.showToast(context, t.getMessage());
                    }
                });
    }

    private void loadingTask1(final Context context) {
        bean = (NewUserInfoBean.DataBean) ObjectSaveUtil.readObject(context, Constants.USER_INFO_BEAN, Constants.USER_INFO_BEAN);
        int id = bean.getID();
        int roleId = bean.getRoleInfoId();
        if (roleId == Constants.ROLE_HEAD_NURSE || roleId == Constants.ROLE_MANAGE || roleId == Constants.ROLE_FACTORY) {
            id = 0;
        }
        GetRetrofit.getInstance().getUnusedGoods(NetAddress.token, NetAddress.machineCode, NetAddress.deptCode, id + "", "1")
                .enqueue(new Callback<UnusedGoodsBean>() {
                    @Override
                    public void onResponse(Call<UnusedGoodsBean> call, Response<UnusedGoodsBean> response) {
                        sbUserIds.delete(0, sbUserIds.length());
                        UnusedGoodsBean data = response.body();
                        isReturn = true;
                        if (data != null) {
                            List<UnusedGoodsBean.DataBean> body = data.getData();
                            if (body != null) {
                                returnHintCount = body.size();
                            } else {
                                returnHintCount = 0;
                            }
                        } else {
                            returnHintCount = 0;
                        }
                        NetAddress.RETURNHINE_COUNT = returnHintCount;
                        endtime = System.currentTimeMillis();
                        if (isTimeout && isWarning) {
                            Message message = allHandler.obtainMessage();
                            message.what = HandlerConstant.RED_COUNT;
                            message.arg1 = timeOutCount;
                            message.arg2 = inventoryWarnCount;
                            message.obj = returnHintCount;
                            allHandler.sendMessage(message);
                        }
                    }

                    @Override
                    public void onFailure(Call<UnusedGoodsBean> call, Throwable t) {
                        isReturn = true;
                        ToastUtil.showToast(context, t.getMessage());
                    }
                });
    }

    public static void getLoginDataCount(final Context context, String id, String dept, final boolean isLogin) {

        final SharedPreferences sharedPreferences = ActivityUtil.getSharedPreferences(context);

        GetRetrofit.getInstance().getLoginData(NetAddress.token, NetAddress.machineCode, id, dept)
                .enqueue(new Callback<LoginBean>() {
                    @Override
                    public void onResponse(Call<LoginBean> call, Response<LoginBean> response) {
                        LoginBean body = response.body();
                        if (body != null) {
                            LoginBean.DataBean data = body.getData();
                            int timeOutCount = data.getExpiredCount();
                            int inventoryWarnCount = data.getStorageCount();
                            int returnHintCount = data.getNotreturningCount();

                            if (isLogin) {
                                SharedPreferences.Editor edit = sharedPreferences.edit();
                                edit.putInt(Constants.TIMEOUT_COUNT, timeOutCount);
                                edit.putInt(Constants.INVENTORY_COUNT, inventoryWarnCount);
                                edit.putInt(Constants.RETURNHINT_COUNT, returnHintCount);
                                edit.commit();

//                                if (!TextUtils.isEmpty(data.getNowTime())) {
//                                    // 设置系统时间
//                                    String stringExtra = TimeUtil.getNowTime(data.getNowTime());
//                                    int year = Integer.parseInt(stringExtra.substring(0, 4));
//                                    int month = Integer.parseInt(stringExtra.substring(5, 7));
//                                    int day = Integer.parseInt(stringExtra.substring(8, 10));
//                                    int hour = Integer.parseInt(stringExtra.substring(11, 13));
//                                    int minute = Integer.parseInt(stringExtra.substring(14, 16));
//                                    int second = Integer.parseInt(stringExtra.substring(17, 19));
//                                    try {
//                                        TimeUtil.setDateTime(year, month, day, hour, minute, second);
//                                    } catch (Exception e) {
//                                        e.printStackTrace();
//                                    }
//                                }

                                Intent intent = new Intent(context, MainActivity.class);
                                context.startActivity(intent);

                                ActivityControl.finishAll();

                            } else {
                                Message message = allHandler.obtainMessage();
                                message.what = HandlerConstant.RED_COUNT;
                                message.arg1 = timeOutCount;
                                message.arg2 = inventoryWarnCount;
                                message.obj = returnHintCount;
                                allHandler.sendMessage(message);
                            }
                        }else {
                            ToastUtil.showToast(context, "登录失败，请重试");
                            allHandler.sendEmptyMessageDelayed(HandlerConstant.FINGER_LOGIN_ERROR_AGIN, 1000);
                            allHandler.sendEmptyMessageDelayed(HandlerConstant.IRIS_LOGIN_ERROR_AGIN, 1000);
                        }
                    }

                    @Override
                    public void onFailure(Call<LoginBean> call, Throwable t) {
                        ToastUtil.showToast(context, "登录失败，请重试");
                        allHandler.sendEmptyMessageDelayed(HandlerConstant.FINGER_LOGIN_ERROR_AGIN, 1000);
                        allHandler.sendEmptyMessageDelayed(HandlerConstant.IRIS_LOGIN_ERROR_AGIN, 1000);
                    }
                });
    }

}
